use std::iter::MapWhile;

// [1652]拆炸弹
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
    pub fn decrypt(code: Vec<i32>, k: i32) -> Vec<i32> {
        let mut ans = vec![0; code.len()];
        if k == 0 {
            return ans;
        }
        let mut left = 0;
        let mut right = 0;
        if k > 0 {
            left = 1;
            right = 0;
        } else {
            left = (code.len() as i32 + k) as usize % code.len();
            right = left - 1;
        }
        let mut sum = 0;
        let mut cnt = 0;
        for i in 0..code.len() {
            while cnt < k.abs() {
                right = (right + 1) % code.len();
                sum += code[right];
                cnt += 1;
            }
            ans[i] = sum;
            sum -= code[left];
            left = (left + 1) % code.len();
            right = (right + 1) % code.len();
            sum += code[right];
        }
        ans
    }
}
//leetcode submit region end(Prohibit modification and deletion)

#[test]
fn main() {
    let code = vec![5, 7, 1, 4];
    let k = 3;
    assert_eq!(Solution::decrypt(code, k), vec![12, 10, 16, 13]);
    let code = vec![1, 2, 3, 4];
    let k = 0;
    assert_eq!(Solution::decrypt(code, k), vec![0, 0, 0, 0]);
    let code = vec![2, 4, 9, 3];
    let k = -2;
    assert_eq!(Solution::decrypt(code, k), vec![12, 5, 6, 13]);
}
